import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { DbService } from 'src/db/db.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { Book } from './entities/book.entity';
@Injectable()
export class BookService {
  @Inject()
  dbService: DbService;
  async list(name: string) {
    const books = await this.dbService.read();
    return name ? books.filter((book) => book.name.includes(name)) : books;
  }

  async findById(id: number) {
    // await this.queryBook(id).catch((error: any) => {
    //   throw error;
    // });
    return (await this.dbService.read()).find((item) => item.id === id);
  }

  async create(createBookDto: CreateBookDto) {
    const book = new Book();
    book.id = Math.floor(Math.random() * 10000);
    book.name = createBookDto.name;
    book.author = createBookDto.author;
    book.description = createBookDto.description;
    book.cover = createBookDto.cover;

    const books: Book[] = await this.dbService.read();
    books.push(book);
    await this.dbService.write(books);
    return book;
  }
  async update(updateBookDto: UpdateBookDto) {
    const books: Book[] = await this.dbService.read();
    const book = books.find((item: Book) => item.id === updateBookDto.id);
    if (!book) {
      throw new BadRequestException('该图书不存在');
    }
    book.name = updateBookDto.name;
    book.author = updateBookDto.author;
    book.description = updateBookDto.description;
    book.cover = updateBookDto.cover;
    await this.dbService.write(books);
    return book;
  }

  async delete(id: number) {
    const books: Book[] = await this.dbService.read();
    const index: number = books.findIndex((item: Book) => item.id === id);
    if (index !== -1) {
      books.splice(index, 1);
      await this.dbService.write(books);
      return '删除成功';
    } else {
      throw new BadRequestException('该图书不存在');
    }
  }

  async queryBook(id: number) {
    const books: Book[] = await this.dbService.read();
    const book = books.find((item: Book) => item.id === id);
    if (!book) {
      throw new BadRequestException('该图书不存在');
    }
  }
}
